import { deleteCart, getCartList, updateCartList } from '@/api/cart'
import { Toast } from 'vant'

export default {
  namespaced: true,
  state () {
    return {
      cartList: []
    }
  },
  mutations: {
    setCartList (state, newList) {
      state.cartList = newList
    },
    toggleCheck (state, id) {
      const goods = state.cartList.find(item => item.goods_id === id)
      goods.isChecked = !goods.isChecked
    },
    toggleAll (state, is) {
      state.cartList.forEach(item => { item.isChecked = is })
    },
    changeCount (state, obj) {
      const goods = state.cartList.find(item => item.goods_id === obj.goodsId)
      if (goods) {
        goods.goods_num = obj.goodsNum
      }
    }
  },
  actions: {
    async getCartAction (ctx) {
      const { data } = await getCartList()
      console.log(data)
      data.list.forEach(item => {
        item.isChecked = true
      })
      ctx.commit('setCartList', data.list)
    },
    async changeCountAction (ctx, obj) {
      ctx.commit('changeCount', obj)
      const res = await updateCartList(obj)
      console.log(res)
    },
    async delSelect (ctx) {
      const selCartList = ctx.getters.selCartList
      const Ids = selCartList.map(item => item.id)
      const res = await deleteCart(Ids)
      ctx.dispatch('cart/getCartAction')
      Toast('删除成功')
      console.log(res)
    }
  },
  getters: {
    // suoyoushangpin
    cartTotal (state) {
      return state.cartList.reduce((sum, item) => sum + item.goods_num, 0)
    },
    // 选中的
    selCartList (state) {
      return state.cartList.filter(item => item.isChecked)
    },
    selCount (state, getters) {
      return getters.selCartList.reduce((sum, item) => sum + item.goods_num, 0)
    },
    selPrice (state, getters) {
      return getters.selCartList.reduce((sum, item) => {
        return sum + (item.goods_num * item.goods.goods_price_min)
      }, 0)
    },
    isAllChecked (state) {
      return state.cartList.every(item => item.isChecked)
    }
  }
}
